# 各城市的地址信息接口

from flask_restful import Resource, fields, marshal_with, marshal

from App.apis.api_constant import HTTP_OK
from App.models.common import My_City

# 字典类型，格式化数据库中data用
city_fields = {
    'id' : fields.Integer(attribute='c_id'),
    'parentId' : fields.Integer(attribute='c_parent_id'),
    'regionName' : fields.String(attribute='c_regionName'),
    'cityCode' : fields.Integer(attribute='c_cityCode'),
    'pinYin' : fields.String(attribute='c_pinYin')
}

class CitiesResource(Resource):

    def get(self):
        letters = My_City.query.all()
        all_letter = []
        for letter in letters:
            if len(all_letter) == 0:
                all_letter.append(letter.c_letter)
            else:
                if letter.c_letter != all_letter[len(all_letter)-1]:
                    all_letter.append(letter.c_letter)      # all_letter 就是所有首字母组成的列表
        # print(all_letter)

        letters_cities = {}
        letters_cities_fields = {}
        # len_letter = len(all_letter)
        for i in all_letter:
            letter_cities = My_City.query.filter(My_City.c_letter == i)
            letters_cities[i] = letter_cities          # 把每个字母 i 对应的所有城市信息条存在letters_cities，形成键值对(未经过格式化)
            letters_cities_fields[i] = fields.List(fields.Nested(city_fields))      #?? 这里是难点，fields序列化的级联嵌套，还用的字典
        # print(letters_cities)
        # print(type(letters_cities_fields))      # 这个继承city_fields的letters_cities_fields也是字典类型
        # print(type(letters_cities))             # 字典类型
        # print(type(city_fields))             # 字典类型

        return {
            'msg':'ok' ,
            'status':HTTP_OK ,
            'data':marshal(letters_cities , letters_cities_fields)
        }


